﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Accountant.DataModel;

namespace Accountant.MySerializer
{
  public class DbSet<T, TContext> : Collection<T>
    where TContext : DbContext
    where T : IEntity<TContext>
  {
    private readonly TContext _context;

    public DbSet(TContext context)
    {
      _context = context;
    }

    public new T Add(T item)
    {
      base.Add(item);
      return item;
    }
    protected override void InsertItem(int index, T item)
    {
      if (item.Context == _context)
      {
        if (_context == AccountantContext.Unbound)
        {
#if DEBUG
          if (Contains(item)) throw new InvalidOperationException();
#endif
          base.InsertItem(index, item);
        }
        else throw new Exception("How did it happen that item is already in context and not in the set yet?");
      }
      else if (_context.IsLoading)
      {
        item.Context = _context;
        base.InsertItem(index, item);
      }
      else
      {
        _context.IsLoading = true;
        item.AbsorbGraphIntoContext(_context, new HashSet<object>());
        _context.IsLoading = false;

//        _context.Absorb(item.Context);
      }
    }
    protected override void RemoveItem(int index)
    {
      throw new NotImplementedException();
    }
//    protected override void ClearItems()
//    {
//      foreach (var item in Items)
//        item.Detach(_context);
//      base.ClearItems();
//    }
  }
}